#include "httpserver.h"
#include <stdlib.h>
#include <stdio.h>
#include "civetweb/civetweb.h"

static const char* const RSP_JSON = "application/json; charset=utf-8";
static const char* const RSP_HTML = "text/html; charset=UTF-8";
static const char* const RSP_TEXT = "text/plain; charset=utf-8";
static const char* const RSP_XML = "application/xml; charset=utf-8";
static const char* const RSP_STREAM = "application/octet-stream";

static void sendRspInfo(const std::string& strRspInfo, const std::string& strType, struct mg_connection* conn)
{
    if (strRspInfo.empty() || !conn) {
        printf(">>> strRspInfo is empty() or mg_connection instance is nullptr.\r\n");
        return;
    }

    char* pData = const_cast<char*>(strRspInfo.c_str());
    if(int iRet = mg_send_http_ok(conn, strType.data(), static_cast<long long>(strRspInfo.size())) < 0) {
        printf(">>> mg_send_http_ok ret (%d) error.\r\n", iRet);
    }

    if (int iRet = mg_write(conn, pData, strRspInfo.size()) <= 0) {
        printf(">>> mg_write ret (%d) error.\r\n", iRet);
    }

    return;
}

void HttpServerBaseHandler::setUrl(std::string strUrl)
{
    m_strUrl = strUrl;
    return;
}

std::string HttpServerBaseHandler::getUrl() const
{
    return m_strUrl;
}

bool HttpServerBaseHandler::handleGet(CivetServer *server, struct mg_connection *conn)
{
    if (!server) {
        return false;
    }

    sendRspInfo("Welcome!!!", RSP_TEXT, conn);
    return true;
}

bool HttpServerBaseHandler::handlePost(CivetServer *server, struct mg_connection *conn)
{
    if (!server) {
        return false;
    }

    std::string data = server->getPostData(conn); // get post request data
    printf(">>> get request data: %s.\r\n", data.data());
    sendRspInfo("{\"message\": \"welcome\"}", RSP_JSON, conn);
    return true;
}

Example1HttpServerHandler::Example1HttpServerHandler()
{
    setUrl("/v1/example1");
}

Example1HttpServerHandler::~Example1HttpServerHandler()
{

}

bool Example1HttpServerHandler::handleGet(CivetServer *server, struct mg_connection *conn)
{
    (void)server;
    (void)conn;

    // TODO
    return true;
}

bool Example1HttpServerHandler::handlePost(CivetServer *server, struct mg_connection *conn)
{
    std::string data = server->getPostData(conn); // get post request data
    printf(">>> get request data: %s.\r\n", data.data());

    // TODO

    return true;
}

